package wang.conge.javasedemo.core.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author conge
 * 2016年7月14日
 */
public class BlockingIOServer {
	public static void main(String[] args) {
		int port = 10000;
		
		int processors = Runtime.getRuntime().availableProcessors();
		ExecutorService threadPool = Executors.newFixedThreadPool(processors);
		ServerSocket server = null;
		
		try {
			server = new ServerSocket(port);
			
			while(true){
				Socket client = server.accept();
				
				//启用线程处理client
				threadPool.execute(()->{
					try{
						InputStream input = client.getInputStream();
						
						StringBuilder sb = new StringBuilder();
						byte[] bytes = new byte[1024];
						while(true){
							int read = input.read(bytes);
							if(read<0){
								break;
							}
							
							String req = new String(bytes);
							req = req.trim();
							sb.append(req);
							if(req.endsWith("END")){
								break;
							}
						}
						
						//TODO service
						System.out.println(sb);
						sb.append("response,END");
						client.getOutputStream().write(sb.toString().getBytes());
						client.getOutputStream().flush();
						
					}catch(IOException e){
						e.printStackTrace();
					}finally {
						if(!client.isClosed()){
							try {
								client.close();
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
				});
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

}
